﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

namespace comm
{
    public enum CodeFillType
    {
        ORM_CONST = 0,
        DEFINE_FILE_CONST = 1,
        TCP_CONST = 2
    }

    public class CodeFill
    {
        public const string END = "public comm.CodeFill FillRegion";

        public static void ReplaceAll(Dictionary<CodeFillType, Func<object, string>> funcDic)
        {
            var asls = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var asl in asls)
            {
                var types = asl.GetTypes();
                foreach (var type in types)
                {
                    if (type.GetInterface(typeof(ICodeReplace).FullName, true) != null)
                    {
                        var icr = (ICodeReplace)Activator.CreateInstance(type);
                        var codeFile = icr.FillRegion();
                        var code = File.ReadAllText(codeFile.FileName);
                        code = Regex.Replace(code, type.Name + " (.+?){(.+?)" + END, new MatchEvaluator(mh =>
                        {
                            return type.Name + " " + mh.Groups[1].Value + "{\r\n#region " + DateTime.Now + "\r\n" + funcDic[codeFile.FillType](icr) + "\r\n#endregion\r\n" + END;
                        }), RegexOptions.Singleline);
                        File.WriteAllText(codeFile.FileName, code);
                    }
                }
            }
        }

        public string FileName { get; private set; }
        public CodeFillType FillType { get; set; }
        public object Obj { get; private set; }

        public CodeFill(CodeFillType fillType, object obj)
        {
            var frame = new StackTrace(true).GetFrame(1);
            FileName = frame.GetFileName();
            FillType = fillType;
            Obj = obj;
        }
    }

    public interface ICodeReplace
    {
        CodeFill FillRegion();
    }
}
